package com.mlm.mlmapp.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.Adapter;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.util.Constants;
import com.mlm.mlmapp.R;
import com.mlm.mlmapp.activity.layoutmanager.SyGridLayoutManager;
import com.mlm.mlmapp.adapter.view.AQProgressDialog;
import com.mlm.mlmapp.adapter.view.GridMarginDecoration;
import com.mlm.mlmapp.adapter.view.listener.CommonItemSelectedListener;
import com.mlm.mlmapp.adapter.view.listener.DialogItemSelectedListener;
import com.mlm.mlmapp.adapter.view.listener.OnRcvScrollListener;
import com.mlm.mlmapp.animation.RecyclAnimation;
import com.mlm.mlmapp.cons.HTTPCons;
import com.mlm.mlmapp.utils.CommonUtils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Receiver;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.ColorRes;
import org.androidannotations.annotations.res.DimensionRes;
import org.androidannotations.annotations.res.StringRes;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

@EActivity(R.layout.hairstyle_view)
public class HairStyleListActivity extends BaseActivity implements HTTPCons,
        CommonItemSelectedListener, DialogItemSelectedListener {
    public static final int DESC = 1;
    public static final int ASC = 2;
    public static final int NORMAL = 0;
    private int mPage = 1;
    private AQuery aq;
    private SylistAdapter adapter;
    List<JSONObject> syListDataset;
    List<JSONObject> typeList;
    private TypeAdapter typeAdapter;
    private int btnStatusAttention;
    private int btnStatusCreated;
    private String currentTypeId = "";
    private boolean isMaxPage = false;
    private String currentAttention = "";
    private String currentCreated = "";
    private Bitmap preBm;
    @StringRes(R.string.all_hairstyle)
    String allHairStyle;
    @ViewById
    Button btn_attention;
    @ViewById
    Button btn_created;
    @ViewById
    Button btn_hairstyle_type;
    @ViewById
    RecyclerView rv_stylist;

    @ViewById
    RelativeLayout rl_type;
    @ViewById
    LinearLayout btn_back;
    @ColorRes(R.color.red)
    int redText;
    @ViewById
    RecyclerView rv_type;
    @DimensionRes(R.dimen.recyclerview_sylist_space)
    float recyclerview_sylist_space;
    private int coutPerPage = 6;

    @AfterViews
    public void init() {
        preBm= BitmapFactory.decodeResource(getResources(),R.drawable.style_default);
        typeList = new ArrayList<>();
        btn_back.setVisibility(View.INVISIBLE);
        btn_style.setCompoundDrawablesWithIntrinsicBounds(null, getResources()
                .getDrawable(R.drawable.stylechecked), null, null);
        btn_style.setTextColor(getResources().getColor(R.color.red));
        String title = getTitle().toString();
        if (!"".equals(title)) {
            ((TextView) this.findViewById(R.id.tv_title)).setText(title);
        }

        aq = new AQuery(this);
        aq.hardwareAccelerated11();
        syListDataset = new ArrayList<>();
        LinearLayoutManager typeLayoutManager = new LinearLayoutManager(this);
        rv_type.setLayoutManager(typeLayoutManager);
        typeAdapter = new TypeAdapter(
                HairStyleListActivity.this);
        rv_type.setAdapter(typeAdapter);
        final GridLayoutManager layoutManager = new SyGridLayoutManager(this, 2);
        rv_stylist.setLayoutManager(layoutManager);

        rv_stylist.addItemDecoration(new GridMarginDecoration(this,
                recyclerview_sylist_space, recyclerview_sylist_space,
                recyclerview_sylist_space, recyclerview_sylist_space));
        // rv_stylist
        // .addItemDecoration(new
        // GridMarginDecoration(this,recyclerview_sylist_space,
        // recyclerview_sylist_space, recyclerview_sylist_space,
        // recyclerview_sylist_space));
        rv_stylist.setItemAnimator(new RecyclAnimation());
        adapter = new SylistAdapter(HairStyleListActivity.this, syListDataset);
        OnRcvScrollListener listener = new OnRcvScrollListener() {

            @Override
            public void onBottom() {
                // TODO Auto-generated method stub
                super.onBottom();
                // mSwipeRefreshWidget.setRefreshing(true);
                updateDataset(mPage);
            }

        };
        rv_stylist.setOnScrollListener(listener);
        rv_stylist.setAdapter(adapter);
        // init sylist date
        updateDataset(mPage);

        aq.progress(new AQProgressDialog(this)).ajax(get_sy_type_action, JSONArray.class,
                new AjaxCallback<JSONArray>() {

                    @Override
                    public void callback(String url, JSONArray object,
                                         AjaxStatus status) {
                        // TODO Auto-generated method stub
                        super.callback(url, object, status);
                        if (status.getCode() == -101) {
                            Toast.makeText(aq.getContext(), "网络异常,请检查网络",
                                    Toast.LENGTH_SHORT);
                            return;
                        }
                        JSONObject obj = new JSONObject();
                        try {
                            JSONObject first = new JSONObject();
                            first.put("id", "");
                            first.put("clasName", allHairStyle);
                            typeList.add(first);
                            for (int i = 0; i < object.length(); i++) {
                                typeList.add(object.getJSONObject(i));
                            }
                            rv_type.getAdapter().notifyDataSetChanged();
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }

                });
        rl_type.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                clearPopup();
            }
        });

    }

    /**
     * desc default,arrow up as ASC, down as DESC
     */
    @Click
    void btn_attention() {
        clearPopup();
        switch (btnStatusAttention) {
            case 0:
                btnStatusAttention = 1;
                currentAttention = "DESC";
                btn_attention.setCompoundDrawables(null, null, CommonUtils
                        .setButtonDrawableRight(this, R.drawable.arrow_up), null);
                btn_attention.setTextColor(redText);
                break;
            case 1:
                btnStatusAttention = 2;
                currentAttention = "ASC";
                btn_attention.setCompoundDrawables(null, null, CommonUtils
                        .setButtonDrawableRight(this, R.drawable.arrow_down), null);
                btn_attention.setTextColor(redText);
                break;
            case 2:
            default:
                currentAttention = "DESC";
                btnStatusAttention = 1;
                btn_attention.setCompoundDrawables(null, null, CommonUtils
                        .setButtonDrawableRight(this, R.drawable.arrow_up), null);
                btn_attention.setTextColor(redText);
        }
        clearDataset();
        updateDataset(mPage);
    }
    @Receiver(actions = "com.mlm.mlmapp.resetArea")
    protected void retArea(Intent intent) {
        typeAdapter.selectID="";
        typeAdapter.notifyDataSetChanged();
        currentAttention = "";
        currentCreated = "";
        currentTypeId = "";
        clearDataset();
        updateDataset(mPage);
        btn_hairstyle_type.setText("发型分类");
        btn_hairstyle_type.setTextColor(Color.parseColor("#9a9a9a"));
        btn_hairstyle_type.setCompoundDrawables(null, null, CommonUtils
                .setButtonDrawableRight(this, R.drawable.screen_arrow_down), null);
        btn_created.setCompoundDrawables(null, null, CommonUtils
                .setButtonDrawableRight(this, R.drawable.arrow_default), null);
        btn_created.setTextColor(Color.parseColor("#9a9a9a"));
        btn_attention.setTextColor(Color.parseColor("#9a9a9a"));
        btn_attention.setCompoundDrawables(null, null, CommonUtils
                .setButtonDrawableRight(this, R.drawable.arrow_default), null);
    }

    /**
     * desc default
     */
    @Click
    void btn_created() {
        clearPopup();
        switch (btnStatusCreated) {
            case 0:
                btnStatusCreated = 1;
                currentCreated = "DESC";
                btn_created.setCompoundDrawables(null, null, CommonUtils
                        .setButtonDrawableRight(this, R.drawable.arrow_up), null);
                btn_created.setTextColor(redText);
                break;
            case 1:
                btnStatusCreated = 2;
                currentCreated = "ASC";
                btn_created.setCompoundDrawables(null, null, CommonUtils
                        .setButtonDrawableRight(this, R.drawable.arrow_down), null);
                btn_created.setTextColor(redText);
                break;
            case 2:
            default:
                currentCreated = "DESC";

                btnStatusCreated = 1;
                btn_created.setCompoundDrawables(null, null, CommonUtils
                        .setButtonDrawableRight(this, R.drawable.arrow_up), null);
                btn_created.setTextColor(redText);
        }
        clearDataset();
        updateDataset(mPage);
    }

    // when change the condition, need clear dataset
    private void clearDataset() {
        mPage = 1;
        this.syListDataset.clear();
        adapter.notifyDataSetChanged();
    }

    @Click
    void btn_hairstyle_type() {

        if (rl_type.getVisibility() == View.VISIBLE)
            typeVisible(View.INVISIBLE);
        else
            typeVisible(View.VISIBLE);
    }

    void updateDataset(int page) {
        StringBuilder url = new StringBuilder(get_sy_img_action);
        url.append("?");
        if (!"".equals(currentAttention)) {
            url.append("collect=" + currentAttention);
            url.append("&");
        }

        if (!"".equals(currentCreated)) {
            url.append("created=" + currentCreated);
            url.append("&");
        }
        if (!"".equals(currentTypeId)) {
            url.append("clasId=" + currentTypeId);
            url.append("&");
        }
        url.append("page=" + page);
        getSylist(url.toString());

    }

    void getSylist(String url) {
        aq.progress(new AQProgressDialog(this)).ajax(url, JSONArray.class, new AjaxCallback<JSONArray>() {

            @Override
            public void callback(String url, JSONArray object, AjaxStatus status) {
                // TODO Auto-generated method stub
                super.callback(url, object, status);
                if (status.getCode() == -101) {
                    Toast.makeText(aq.getContext(), "网络异常,请检查网络",
                            Toast.LENGTH_SHORT);
                    return;
                }
                int startindex=syListDataset.size();
                if(object != null &&object.length()==0){
                    Toast.makeText(HairStyleListActivity.this, "没有更多内容了", Toast.LENGTH_SHORT).show();
                }
                if (object != null && object.length() > 0) {
                    for (int i = 0; i < object.length(); i++) {
                        try {
                            syListDataset.add(object.getJSONObject(i));
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    mPage++;
                    adapter.notifyItemRangeInserted(startindex,object.length());
                }
            }

        });

    }

    class SylistAdapter extends
            Adapter<SylistAdapter.SyViewHolder> {
        private CommonItemSelectedListener mOnCommonItemSelectedListener;
        List<JSONObject> array;
        Context con;
        private int nextPageFlag = 6;

        public SylistAdapter(Context con, List<JSONObject> array) {
            this.con = con;
            this.mOnCommonItemSelectedListener = (CommonItemSelectedListener) con;
            this.array = array;

        }

        public String getID(int position) {

            JSONObject currObj = array.get(position);
            return CommonUtils.getJsonString(currObj, "id");

        }

        @Override
        public int getItemCount() {
            return array.size();
        }

        class SyViewHolder extends ViewHolder implements OnClickListener {
            TextView tv_sy_intro;
            ImageView iv_sy_img;

            public SyViewHolder(View view) {
                super(view);
                tv_sy_intro = (TextView) view.findViewById(R.id.tv_sy_intro);
                iv_sy_img = (ImageView) view.findViewById(R.id.iv_sy_img);
                iv_sy_img.setOnClickListener(this);
            }

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                mOnCommonItemSelectedListener.onItemClick(arg0, getPosition());
            }
        }

        @Override
        public SyViewHolder onCreateViewHolder(ViewGroup parent, int arg1) {
            // TODO Auto-generated method stub
            SyViewHolder holder = new SyViewHolder(LayoutInflater.from(
                    HairStyleListActivity.this).inflate(
                    R.layout.hair_style_list_item, parent, false));
            return holder;
        }

        @Override
        public void onBindViewHolder(SyViewHolder holder, int position) {
            // TODO Auto-generated method stub
            JSONObject obj = array.get(position);

            aq.id(holder.iv_sy_img).image(
                    CommonUtils.getJsonString(obj, "hairPhotoUrl"), true, true,
                    120, 0, preBm, Constants.FADE_IN);
            holder.tv_sy_intro.setText(CommonUtils.getJsonString(obj,
                    "infoDescription"));
        }
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
    }

    class TypeAdapter extends Adapter<TypeAdapter.TypeViewHolder> {
        private DialogItemSelectedListener mOnDialogItemSelectedListener;
        Context con;
        public String selectID;
        public TypeAdapter(Context con) {
            this.con = con;
            this.mOnDialogItemSelectedListener = (DialogItemSelectedListener) con;

        }

        public String getID(int position) {
            return CommonUtils.getJsonString(typeList.get(position),
                    "id");
        }

        @Override
        public int getItemCount() {
            return typeList.size();
        }

        class TypeViewHolder extends ViewHolder implements OnClickListener {
            TextView tv_sy_intro;

            public TypeViewHolder(View view) {
                super(view);
                tv_sy_intro = (TextView) view.findViewById(R.id.tv_dialog_item);
                tv_sy_intro.setClickable(true);
                tv_sy_intro.setOnClickListener(this);
            }

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                selectID= getJsonString(typeList.get(getAdapterPosition()),"id");
                TextView v = (TextView) arg0;
                mOnDialogItemSelectedListener.onDialogItemClick(arg0,
                        getPosition(), v.getText().toString());
                notifyDataSetChanged();
            }
        }

        @Override
        public TypeViewHolder onCreateViewHolder(ViewGroup parent, int arg1) {
            // TODO Auto-generated method stub
            TypeViewHolder holder = new TypeViewHolder(LayoutInflater.from(
                    HairStyleListActivity.this).inflate(
                    R.layout.dialog_header_item_view, parent, false));
            return holder;
        }

        @Override
        public void onBindViewHolder(TypeViewHolder holder, int position) {
            // TODO Auto-generated method stub
            JSONObject obj = typeList.get(position);

            holder.tv_sy_intro.setText(CommonUtils.getJsonString(obj,
                    "clasName"));
            if(selectID!=null&&selectID.equals(getJsonString(obj,"id"))){
                holder.tv_sy_intro.setBackgroundColor(Color.parseColor("#9a9a9a"));
                holder.tv_sy_intro.setTextColor(Color.WHITE);
            }else{
                holder.tv_sy_intro.setBackgroundColor(Color.WHITE);
                holder.tv_sy_intro.setTextColor(Color.parseColor("#9a9a9a"));
            }
        }

    }

    @Override
    public void onItemClick(View v, int position) {
        // TODO: 2016/3/25
        String linkType = CommonUtils.getJsonString(syListDataset.get(position), "linkType");
        if ("2".equals(linkType)) {
            HairStylePublicDetailActivity_
                    .intent(this)
                    .extra("id",
                            CommonUtils.getJsonString(syListDataset.get(position),
                                    "id")).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).start();
        } else {
            HairStyleDetailActivity_
                    .intent(this)
                    .extra("id", CommonUtils.getJsonString(syListDataset.get(position), "id")).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).start();
        }

    }

    @Override
    public void onDialogItemClick(View v, int position, String typeName) {
        // TODO Auto-generated method stub
        typeAdapter = (TypeAdapter) rv_type.getAdapter();
        currentTypeId = typeAdapter.getID(position);
        if(position!=0) {
            btn_hairstyle_type.setText(typeName);
            btn_hairstyle_type.setTextColor(Color.parseColor("#ea2929"));
            btn_hairstyle_type.setCompoundDrawables(null, null, CommonUtils
                    .setButtonDrawableRight(this, R.drawable.screen_arrow_up), null);
        }else{
            btn_hairstyle_type.setText("发型分类");
            btn_hairstyle_type.setTextColor(Color.parseColor("#9a9a9a"));
            btn_hairstyle_type.setCompoundDrawables(null, null, CommonUtils
                    .setButtonDrawableRight(this, R.drawable.screen_arrow_down), null);
        }

        typeVisible(View.INVISIBLE);
        clearDataset();
        updateDataset(mPage);
    }

    // as the function name !

    private void typeVisible(int flag) {
        if (flag == View.INVISIBLE) {
            rl_type.setVisibility(View.INVISIBLE);
        } else {
            rl_type.setVisibility(View.VISIBLE);
        }
    }
    private void clearPopup(){
        if(rl_type.getVisibility()==View.VISIBLE){
            rl_type.setVisibility(View.INVISIBLE);
        }
    }
    @Click
    void btn_home() {
        clearPopup();
        MainActivity_.intent(this).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).start();
    }

    @Click
    void btn_dresser() {
        clearPopup();
        HairDresserListActivity_.intent(this).extra("bookflag",false).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).start();
    }

    @Click
    void btn_appointment() {
        clearPopup();
        BookActivity_.intent(this).start();
    }

    @ViewById
    Button btn_style;

    @Click
    void btn_style() {
        // HairStyleListActivity_.intent(this).start();
        clearPopup();
    }

    @Click
    void btn_userinfo() {
        clearPopup();

        UserInfoActivity_.intent(this).flags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT).start();
    }


    private long exitTime = 0;
    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub

        if(rl_type.getVisibility()==View.VISIBLE){
            clearPopup();
            return ;
        }
        if((System.currentTimeMillis()-exitTime) > 2000){
            Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
//            finish();
            finishApplication();
        }
    }
}
